package com.epfuse.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.epfuse.cloud.admin.api.entity.SysUser;

import com.epfuse.cloud.admin.mapper.SysUserMapper;
import com.epfuse.cloud.admin.service.AppService;
import com.epfuse.cloud.common.core.constant.CacheConstants;
import com.epfuse.cloud.common.core.constant.SecurityConstants;
import com.epfuse.cloud.common.core.exception.ErrorCodes;
import com.epfuse.cloud.common.core.util.MsgUtils;
import com.epfuse.cloud.common.core.util.R;
import io.springboot.sms.core.SmsClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/7/18  21:40
 */
@Slf4j
@Service
@AllArgsConstructor
public class AppServiceImpl implements AppService {

    private final RedisTemplate redisTemplate;

    private final SysUserMapper userMapper;

    private final SmsClient smsClient;
    /**
     * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
     * @param phone 手机号
     * @return code
     */
    @Override
    public R<Boolean> sendSmsCode(String phone) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = Wrappers.<SysUser>query()
                .lambda()
                .eq((SFunction<SysUser, Object>) SysUser::getPhone, phone);
        List<SysUser> userList = userMapper.selectList(lambdaQueryWrapper);

        if (CollUtil.isEmpty(userList)) {
            log.info("手机号未注册:{}", phone);
            return R.ok(Boolean.FALSE, MsgUtils.getMessage(ErrorCodes.SYS_APP_PHONE_UNREGISTERED, phone));
        }
        Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + phone);

        if (codeObj != null) {
            log.info("手机号验证码未过期:{}，{}", phone, codeObj);
            return R.ok(Boolean.FALSE, MsgUtils.getMessage(ErrorCodes.SYS_APP_SMS_OFTEN));
        }

        String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
        log.info("手机号生成验证码成功:{},{}", phone, code);

        redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + phone, code, SecurityConstants.CODE_TIME,
                TimeUnit.SECONDS);
        // 调用短信通道发送
        this.smsClient.sendCode(code, phone);

        return R.ok(Boolean.TRUE, code);
    }
}
